package com.yhh.college_information_platform.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yhh.college_information_platform.common.PageResult;
import com.yhh.college_information_platform.common.ResultCode;
import com.yhh.college_information_platform.entity.Favorite;
import com.yhh.college_information_platform.entity.Resource;
import com.yhh.college_information_platform.exception.BusinessException;
import com.yhh.college_information_platform.mapper.FavoriteMapper;
import com.yhh.college_information_platform.mapper.ResourceMapper;
import com.yhh.college_information_platform.service.FavoriteService;
import com.yhh.college_information_platform.service.ResourceService;
import com.yhh.college_information_platform.vo.ResourceVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 收藏Service实现类
 *
 * @author yhh
 * @date 2025-10-25
 */
@Slf4j
@Service
public class FavoriteServiceImpl implements FavoriteService {

    @Autowired
    private FavoriteMapper favoriteMapper;

    @Autowired
    private ResourceMapper resourceMapper;

    @Autowired
    private ResourceService resourceService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addFavorite(Long userId, Long resourceId) {
        // 1. 检查资料是否存在
        Resource resource = resourceMapper.selectById(resourceId);
        if (resource == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR, "资料不存在");
        }

        // 2. 检查是否已经收藏
        LambdaQueryWrapper<Favorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Favorite::getUserId, userId)
                .eq(Favorite::getResourceId, resourceId);
        Favorite existFavorite = favoriteMapper.selectOne(wrapper);
        
        if (existFavorite != null) {
            throw new BusinessException(ResultCode.PARAM_ERROR, "已经收藏过该资料");
        }

        // 3. 添加收藏记录
        Favorite favorite = new Favorite();
        favorite.setUserId(userId);
        favorite.setResourceId(resourceId);
        favoriteMapper.insert(favorite);

        // 4. 更新资料的收藏次数
        resource.setFavoriteCount(resource.getFavoriteCount() + 1);
        resourceMapper.updateById(resource);

        log.info("用户 {} 收藏了资料 {}", userId, resourceId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeFavorite(Long userId, Long resourceId) {
        // 1. 查找收藏记录
        LambdaQueryWrapper<Favorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Favorite::getUserId, userId)
                .eq(Favorite::getResourceId, resourceId);
        Favorite favorite = favoriteMapper.selectOne(wrapper);
        
        if (favorite == null) {
            throw new BusinessException(ResultCode.PARAM_ERROR, "未收藏该资料");
        }

        // 2. 删除收藏记录
        favoriteMapper.deleteById(favorite.getId());

        // 3. 更新资料的收藏次数
        Resource resource = resourceMapper.selectById(resourceId);
        if (resource != null && resource.getFavoriteCount() > 0) {
            resource.setFavoriteCount(resource.getFavoriteCount() - 1);
            resourceMapper.updateById(resource);
        }

        log.info("用户 {} 取消收藏资料 {}", userId, resourceId);
    }

    @Override
    public Boolean isFavorited(Long userId, Long resourceId) {
        LambdaQueryWrapper<Favorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Favorite::getUserId, userId)
                .eq(Favorite::getResourceId, resourceId);
        Long count = favoriteMapper.selectCount(wrapper);
        return count > 0;
    }

    @Override
    public PageResult<ResourceVO> getUserFavorites(Long userId, Integer current, Integer size) {
        // 1. 查询用户的收藏记录
        LambdaQueryWrapper<Favorite> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Favorite::getUserId, userId)
                .orderByDesc(Favorite::getCreateTime);
        
        Page<Favorite> page = new Page<>(current, size);
        Page<Favorite> favoritePage = favoriteMapper.selectPage(page, wrapper);

        // 2. 获取资料ID列表
        List<Long> resourceIds = favoritePage.getRecords().stream()
                .map(Favorite::getResourceId)
                .collect(Collectors.toList());

        // 3. 查询资料详情
        List<ResourceVO> resourceVOList = resourceIds.stream()
                .map(id -> {
                    try {
                        return resourceService.getResourceById(id, userId);
                    } catch (Exception e) {
                        log.warn("获取资料详情失败：{}", id, e);
                        return null;
                    }
                })
                .filter(vo -> vo != null)
                .collect(Collectors.toList());

        return new PageResult<>(resourceVOList, favoritePage.getTotal(), favoritePage.getSize(), favoritePage.getCurrent());
    }
}

